{{extend 'layout.html'}}
<script src="{{=URL('static','js/grouping_ajax.js')}}"></script>
{{types=[OPTION(type, _value=type) for type in ['mobile','landline','email']]}}
{{types.insert(0, OPTION('Select Contact Type', _value=''))}}

<script>

var user_id = {{=id}};

$(function(){
    $('[name=groups]').keyup(showgroups)
    click_once_group();    
})

function addgroups(widget){    
    groups = $.grep(groups, function(group){ return group.role != widget.target.name } )
    
    $.ajax({
        url: '/msghandler/default/insert_ajax',
        data: 'group=' + this.id  + '&id=' + user_id + '&table=user_group'
        })             
    
    td1 = $('<img>').attr({
            src:'/msghandler/static/images/delete.png',
            class:'groups-add',
            hidden:true,
            id: 'img' + widget.target.id,
            name: widget.target.name,
        });

    $(widget.target).parent().fadeOut(function() { $(this).remove(); });
    $('#tr-groups-new table tr').append($('<td class="top-td">').append($('<span>'+ widget.target.name +'</span>'),td1));
    
    $('.groups-add').unbind();
    click_once_group();
}

{{if auth.has_membership('Admin'):}}    
    $('.del-row').live('click', function(){
        var answer = confirm('Are you sure you want to delete this?')
        if (answer){
            $.ajax({
                url: '{{=URL('contacts','delete')}}',
                data: 'id=' + this.name,
                context: this,
                success: function(data){
                    msg = 'The contact has been successfully deleted.'
                    $(this).parent().parent().fadeOut(1000, function(){ $(this).remove()})
                    $('.flash').html(msg).slideDown(function(){ $('.flash').delay(500).fadeOut(function(){$('.flash').html('')});});
                }                
            })        
        }     
    })
{{pass}}    

    $('.update-row').live('click',function(){
        contact_type = $(this).parent().prev().prev().children().first().val()
        contact_info = $(this).parent().prev().children().first().val() 
    
        if(contact_type =='') {alert('Please select a contact type.'); return }
        if(contact_info ==''){alert('Contact info should not be blank.'); return }
        $.ajax({
            url: '{{=URL('contacts','update')}}',
            data: 'id=' + this.name +'&' + 'contact_type=' + contact_type + '&' + 'contact_info=' + contact_info,
            context: $(this).parent().parent(),
            success: function(data){
                
                if(data == 0) msg = 'Contact successfully updated.'
                $('.flash').html(msg).slideDown(function(){ $('.flash').delay(3000).fadeOut(function(){$('.flash').html('')});});
            }
        })        
    })

    $('#add-contact').live('click', function(){
        contact_type = $('select[name=contact_type_new]').first().val()
        contact_info = $('input[name=contact_info_new]').val()
        if(contact_type == '') {alert('Contact Type should not be blank.'); return }
        if(contact_info == ''){alert('Contact Info should not be blank.'); return }
    
        $.ajax({
            url: '{{=URL('contacts','create')}}',
            data: 'contact_type=' + contact_type + '&' + 'contact_info=' + contact_info + '&' + 'user_id='+user_id,
            success: function(data){
                if(data != 0) {
                    msg = 'Contact is successfully added.'
                    contact_type = $('select[name=contact_type_new]').first().val()
                    contact_info = $('input[name=contact_info_new]').val()
{{if auth.has_membership('Admin'):}}  
    $('#add-row').before('<tr><td></td><td>{{=SELECT('mobile','landline','email', _name='contact_type')}}</td><td><input type="text" value="'+contact_info+'"></td><td><a class="update-row" name="'+data+'">Update</a> | <a class="del-row" name="'+data+'">Delete</a></td></tr>')                        
{{else:}}
    $('#add-row').before('<tr><td></td><td><input type="text" value="'+contact_type+'"></td><td><input type="text" value="'+contact_info+'"></td><td><a class="update-row" name="'+data+'">Update</a></td></tr>')                        
{{pass}}                    

                    $('select[name=contact_type]').last().val(contact_type)
                    $('select[name=contact_type_new]').val('')
                    $('input[name=contact_info_new]').val('')                        
                }
            
                $('.flash').html(msg).slideDown(function(){ $('.flash').delay(3000).fadeOut(function(){$('.flash').html('')});});
            }
        }) 
    })



function click_once_group(){
    $('.groups-add').one('click', function(){
                $(this).parent().fadeOut( function() { $(this).remove();});
                id = parseInt(this.id.split('imgt')[1]);
                tag = {id:id, role:this.name};
                groups.push(tag); 
                $.ajax({
                    url: '/msghandler/default/delete_ajax',
                    data: 'group=' + id  + '&id=' + user_id + '&table=user_group'
                })             
               showgroups();                 
    });
}
</script>
<style>
.info {
    text-align : center;
    font-size : smaller;
    font-style : italic;
}
</style>
{{=json}}
{{=form.custom.begin}}
<table>
<tr>
<td>
<table>
<tr>
{{=TD(form.custom.widget.first_name)}}
{{=TD(form.custom.widget.last_name)}}
{{if auth.has_membership('Admin'):}}
{{=TD(LABEL('Active: '),form.custom.widget.is_active)}}
{{pass}}
</tr>
{{=TR(TD('First Name'),TD('Last Name'), _class='info')}}
<tr>
{{=TD(form.custom.widget.username)}}
{{if auth.has_membership('Admin') and auth.user.id != id:}}
{{=TD(A('Change password', _href=URL('change_password', args=id)))}}
{{pass}}
</tr>
{{=TR(TD('Username'), _class='info')}}
</table>
</td>
</tr>    
{{=TR(TD(HR()))}}
<tr>
    <td>
        <table>
            <tr>
    {{=TD(LABEL('Groups:'))}}
    {{=TD(form.custom.widget.groups)}}
    <td id="tr-groups-new">
        <table>
            <tr>
                {{for group in groups:}}
                    {{=TD(SPAN(group.group_id.role), 
                          IMG(_src=URL('static', 'images/delete.png'), _hidden=True, 
                                _class='groups-add', _id='imgt'+`group.group_id.id`, _name=group.group_id.role), _class='top-td')}}
                {{pass}}
            </tr>
        </table>
    </td>    
            </tr>
    {{=TR(TD(), TD(DIV(_id='new-groups')))}}
    {{=TR(TD(LABEL('PRC #:')), TD(form.custom.widget.prc))}}    
    {{=TR(TD(LABEL('Profession:')), TD(form.custom.widget.profession))}}
        </table>    
</tr>
{{=TR(TD(HR()))}}
{{=TR(TD(LABEL('Contact Information')), TD())}}
<tr><td>
<table width='100%'>
{{=TR(TH(), TH('Type'),TH('Details'))}}

{{for contact in contacts:}}
    {{=TR(TD(),TD(SELECT(types, _name='contact_type', value=contact.contact_type)), TD(INPUT(_value=contact.contact_info)),
    TD(A('Update', _name=contact.id, _class='update-row'),' | ',
       A('Delete',  _name=contact.id, _class='del-row')))}}
{{pass}}
{{=TR(TD(),TD(SELECT(types, _name='contact_type_new', value='')), \
      TD(INPUT(_name='contact_info_new', _placeholder='insert contact details here')), \      
      TD(A('Add', _id='add-contact')), _id='add-row')}}

</table>
</td></tr>
{{=TR(BR())}}
{{=TR(TD(form.custom.submit))}}
</table>
{{=form.custom.end}}
